<?php

namespace App\Http\Controllers;

use App\Models\Count;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CountController extends Controller
{
    public function count(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nausea_count' => 'required|integer|min:0|max:1000',
            'vomit_count' => 'required|integer|min:0|max:1000',
        ]);
        if ($validator->fails()) {
            return fail($validator->errors()->first(), '1005');
        }
        $user         = $request->user();
        $nausea_count = $request->input('nausea_count');
        $vomit_count  = $request->input('vomit_count');
        //今天是否已经统计过
        $user_count = Count::where('user_id', $user->id)->where('created_at', '>=', Carbon::today())->first();
        if ($user_count) {
            $count_model = $user_count;
        } else {
            $count_model             = new Count();
            $count_model->created_at = Carbon::now();
        }
        $count_model->user_id    = $user->id;
        $count_model->nausea     = $nausea_count;
        $count_model->vomit      = $vomit_count;
        $count_model->updated_at = Carbon::now();
        if (!$count_model->save()) {
            return fail('提交失败，请重试', '1006');
        }
        return success();
    }

    public function userInfo(Request $request)
    {
        $user                 = $request->user();
        $data ['username']    = $user->username;
        $data ['taking_time'] = strtotime($user->taking_time);
        $count                = Count::where('user_id', $user->id)->where('created_at', '>=', Carbon::today())->first();
        if ($count) {
            $data ['today_nausea_count'] = $count->nausea;
            $data ['today_vomit_count']  = $count->vomit;
        } else {
            $data ['today_nausea_count'] = 0;
            $data ['today_vomit_count']  = 0;
        }
        return success($data);
    }

    public function countRecord(Request $request)
    {
        $user   = $request->user();
        $counts = Count::where('user_id', $user->id)->orderBy('id', 'desc')->paginate(10);
        $taking_day = $user->taking_time;
        $datetime_start = new \DateTime(date('Y-m-d',strtotime($taking_day)));
        foreach ($counts as $count){
            $datetime_end = new \DateTime(date('Y-m-d',strtotime($count->updateed_at)));
            $days = $datetime_start->diff($datetime_end)->days+1;
            $count->day = $days;
            $count->time = $count->updated_at->timestamp;
            unset($count->user_id,$count->username,$count->created_at,$count->updated_at);
        }
        return success(['record'=>$counts]);
    }


}
